package cn.chiship.bs.api.biz.controller;


import cn.chiship.bs.api.core.util.Base64ToMultipartFile;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.annotation.NoVerificationAppIdAndKey;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.RandomUtil;
import cn.chiship.sdk.third.storage.FileStorageService;
import cn.chiship.sdk.third.storage.enums.DfsEnum;
import cn.chiship.sdk.third.storage.factory.DfsFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;

/**
 * @author lijian
 */

/**
 * @author lijian
 */
@RequestMapping("/file")
@Api(tags = "文件上传控制器")
@NoVerificationAppIdAndKey
@RestController
public class UploadController {

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    @NoParamsSign
    public ResponseEntity<BaseResult> upload(@RequestParam("file") MultipartFile file) throws Exception {
        return multipartFileUpload(file);
    }

    @ApiOperation(value = "文件上传(UE富文本编辑器)")
    @PostMapping("/ueUpload")
    @NoParamsSign
    public Object ueUpload(@RequestParam("upfile") MultipartFile file) throws Exception {
        return multipartFileUpload(file);
    }


    @ApiOperation(value = "base64图片上传（body）")
    @PostMapping("/base64Upload")
    @NoParamsSign
    public ResponseEntity<BaseResult> pictureUpload(@RequestBody Map<String, String> map) throws Exception {
        MultipartFile file = Base64ToMultipartFile.base64Convert(map.get("base64"));
        return multipartFileUpload(file);
    }

    @ApiOperation(value = "base64图片上传（Form）")
    @PostMapping("/base64UploadForm")
    @NoParamsSign
    public ResponseEntity<BaseResult> base64UploadForm(String base64) throws Exception {
        MultipartFile file = Base64ToMultipartFile.base64Convert(base64);
        return multipartFileUpload(file);
    }

    private ResponseEntity<BaseResult> multipartFileUpload(MultipartFile file) throws IOException {
        String originalName = file.getOriginalFilename();
        String fileExt = originalName.substring(originalName.lastIndexOf(".") + 1);
        String fileName = RandomUtil.uuidLowerCase() + "." + fileExt;
        FileStorageService fileStorageService = DfsFactory.getFileStorageService(DfsEnum.getDfsEnum(1));
        BaseResult baseResult = fileStorageService.upload(
                file.getInputStream(),
                "chiship_bs01",
                fileName
        );
        return new ResponseEntity<>(BaseResult.ok(baseResult.getData().toString()), HttpStatus.OK);
    }
}